package com.xuruzi.demo.util;

import com.alibaba.fastjson.JSON;
import com.xuruzi.demo.util.response.AccessTokenResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Observable;
import java.util.concurrent.TimeUnit;

/**
 * Created by xuruzi on 2020/3/27.
 */
@Service
public  class ApiConfig extends Observable implements Serializable {
    private static final Logger logger = LoggerFactory.getLogger(ApiConfig.class);

    @Resource
    RedisTemplate redisTemplate;

    private String accessToken;
    private String lockStatusKey = "lockStatus";

    public ApiConfig(){

    }
    /**
     * 获取access_token
     * @return
     */
    public String getAccessToken(){
        long now = System.currentTimeMillis();
        Long expireTime = redisTemplate.getExpire("access_token");//获取token过期时间
        if(expireTime == null || expireTime < 100 || this.accessToken == null){
            RedisAtomicLong redisAtomicLong = new RedisAtomicLong(lockStatusKey,
                    redisTemplate.getConnectionFactory());
            // 0 为未锁定状态 1为锁定状态;
            //当access_token过期时间还剩下100秒时,重新刷新token;
            if(redisAtomicLong.compareAndSet(0,1)){
                logger.info("准备刷新access_token......");
                initToken();
                redisTemplate.opsForValue().set(lockStatusKey,0);
            }
        }
        return this.accessToken;
    }


    /**
     * 初始化和重新获取access_token
     */
    public void initToken(){
        logger.info("开始初始化access_token......");
        StringBuilder url = new StringBuilder();
        url.append("http://")
                .append(WxUtils.getDomain()).append("/cgi-bin/gettoken?")
                .append("corpid=").append(WxUtils.getCorpId()).append("&")
                .append("corpsecret=").append(WxUtils.getAgentSecret());
        NetWorkCenter.doGetRequest(url.toString(), null, new NetWorkCenter.ResponseCallback() {
            @Override
            public void onResponse(int resultCode, String result) {
                if (resultCode == 200) {
                    AccessTokenResponse response = JSON.parseObject(result,AccessTokenResponse.class);
                    logger.info("获取access_token ==== " + response.getAccessToken());
                    ApiConfig.this.accessToken = response.getAccessToken();

                    //将获取的token放入redis缓存
                    redisTemplate.opsForValue().set("access_token", response.getAccessToken(), 7200, TimeUnit.SECONDS);
//                    redisCacheService.set("access_token",response.getAccessToken(),7200);
                }
            }
        });
    }




}
